#coding=utf-8

import numpy
from sdsource.models import Price
from sdsource.exception import NoPriceError
from stconfig import dzh_dir

def get_histprices_from_file(fn):
    tmp = numpy.fromfile(open(fn, 'rb'), 'i')
    tmp.shape =tmp.size/10, 10
    #return tmp
    
    rs = []
    
    for d in tmp:
    
        p = Price()
        p.code = code
        
        dt = str(d[0])
        p.date = '-'.join([dt[:4], dt[4:6], dt[6:]])
        
        p.open = d[1]/1000.0
        p.highest = d[2]/1000.0
        p.lowest = d[3]/1000.0
        p.close = d[4]/1000.0
        
        p.amount = long(d[5]) * 1000
        p.volume = long(d[6]) * 100
        
        rs.append(p)
        
    return rs

def get_histprices(code, market='sh'):
    
    mc2df = {'sh':'%s/DATA/SHase/Day/%s.day'%(dzh_dir, code),
             'sz':'%s/DATA/SZnse/Day/%s.day'%(dzh_dir, code),
            }
    fn = mc2df[market]
     
    tmp = numpy.fromfile(open(fn, 'rb'), 'i')
    tmp.shape =tmp.size/10, 10
    #return tmp
    
    rs = []
    
    for d in tmp:
    
        p = Price()
        p.code = code
        
        dt = str(d[0])
        p.date = '-'.join([dt[:4], dt[4:6], dt[6:]])
        
        p.open = d[1]/1000.0
        p.highest = d[2]/1000.0
        p.lowest = d[3]/1000.0
        p.close = d[4]/1000.0
        
        p.amount = long(d[5]) * 1000
        p.volume = long(d[6]) * 100
        
        rs.append(p)
        
    return rs

def price_on(code, tddate, market='sh'):

    ps = get_histprices(code, market)
    for p in ps:
        if p.date == tddate:
            return p
    raise NoPriceError(code, tdate)
    
def prices_since(code, tddate, market='sh'):

    ps = get_histprices(code, market)
    for i in range(len(ps)):
        if ps[i].date >= tddate:
            return ps[i:]

if __name__ == '__main__':
    pass
    
    
